/**
 * Created by zhangbin on 16/2/22.
 */

$(function () {
    $('#addUserWin').window('close');
    $('#updateUserRole').window('close');
    //grid.bind();
    //AddUser(); //添加用户
    //EditUser(); //编辑用户
    //DeleteUser(); //删除用户
    //SetUserPassword(); //设置用户密码
    $('#ffUser').form({
        url: '/sec/addUser.do',
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (data) {
            $("#addUserWin").window('close');
            $("#user_datagrid").datagrid('reload');
        }
    });

    $('#user_datagrid').datagrid({
        toolbar: [{
            iconCls: 'icon-reload',
            text: '刷新',
            handler: function () {
                $('#user_datagrid').datagrid('reload');
            }
        }, '-', {
            iconCls: 'icon-add',
            text: '添加',
            handler: function () {
                if ($(this).linkbutton('options').disabled == true) {
                    return;
                }
                $('#addUserWin').window('open');
                $('#user_datagrid').datagrid('reload');
            }
        }, '-', {
            iconCls: 'icon-edit',
            text: '修改',
            handler: function () {
                var selectRow = $('#user_datagrid').datagrid('getSelected');
                var row = $('#user_datagrid').datagrid('getRowIndex', selectRow);
                if (selectRow != null) {
                    $('#user_datagrid').datagrid('beginEdit', row);
                }
            }
        }, {
            iconCls: 'icon-save',
            text: '保存',
            handler: function () {
                var selectRow = $('#user_datagrid').datagrid('getSelected');
                var row = $('#user_datagrid').datagrid('getRowIndex', selectRow);
                if (selectRow != null) {
                    $('#user_datagrid').datagrid('endEdit', row);
                }

                $.post('/sec/updateSecUser', {
                        id: selectRow.id,
                        loginName: selectRow.loginName,
                        userPassword: selectRow.userPassword
                    },
                    function (resp) {
                        if (resp == 'SUCCESS') {
                            $('#user_datagrid').datagrid('reload');
                        } else {
                            alert('操作失败!');
                            $('#user_datagrid').datagrid('reload');
                        }
                    }
                )
                ;
            }
        }, {
            iconCls: 'icon-undo',
            text: '取消',
            handler: function () {
                var selectRow = $('#user_datagrid').datagrid('getSelected');
                var row = $('#user_datagrid').datagrid('getRowIndex', selectRow);
                $('#user_datagrid').treegrid('cancelEdit', row);
            }
        }, '-', {
            iconCls: 'icon-cancel',
            text: '删除',
            handler: function () {
                if ($(this).linkbutton('options').disabled == true) {
                    return;
                }
                var selectRow = grid.getSelectedRow();

                if (selectRow) {
                    //if (selectRow.Id != '' && selectRow.Id == curUserinfo.id) {
                    //    $.messager.alert('警告提示', '不能删除当前登录用户！', 'warning');
                    //    return false;
                    //}
                    //
                    //if(selectRow.UserName != '' && selectRow.UserName == 'Administrator')
                    //{
                    //    $.messager.alert('警告提示', '不能删除超级管理员用户！', 'warning');
                    //    return false;
                    //}

                    $.messager.confirm('询问提示', '确认要删除所选用户吗？', function (data) {
                        if (data) {
                            $.ajax('/sec/delUser.do?secUserId=' + selectRow.id, function (msg) {
                                if (msg == '1') {
                                    $.messager.alert('成功提示', '所选用户删除成功！');
                                    $('#user_datagrid').datagrid('reload');
                                } else {
                                    $.messager.alert('错误提示', msg, 'error');
                                }
                            });
                            //$.post('/sec/delUser.do/' + selectRow.id, selectRow.id,
                            //    function (resp) {
                            //        if (resp == '1') {
                            //            $('#tg').treegrid('reload');
                            //        } else {
                            //            alert('操作失败!');
                            //        }
                            //    }
                            //);
                        }
                    });
                }
                else {
                    top.$('#notity').jnotifyAddMessage({text: '请选择要删除的用户。', permanent: false, type: 'warning'});
                    return;
                }
            }
        }, '-', {
            iconCls: 'icon-edit',
            text: '修改用户角色',
            handler: function () {

                var selectRow = $('#user_datagrid').datagrid('getSelected');
                var row = $('#user_datagrid').datagrid('getRowIndex', selectRow);
                if (selectRow != null) {
                    $('#updateUserRole').window('open');
                    $("input[name='loginNameUserRole']").val(selectRow.loginName);

                    $.post('/sec/getUserRole/' + selectRow.id, '',
                        function (resp) {
                            $('#roleIdUserRole').combobox('setValue', resp);
                        }
                    )
                    ;
                } else {
                    $.messager.alert("提示", "请选择一条记录!", "info");
                }
            }
        }
            //     ,'-',{
            //     iconCls: 'icon-search',
            //     text: '重置密码',
            //     handler: function(){
            //         if ($(this).linkbutton('options').disabled == true) {
            //             return;
            //         }
            //         var selectRow = grid.getSelectedRow();
            //         if (selectRow != null) {
            //             top.$('#d').hDialog({ width: 300, height: 160, title: '设置用户密码', iconCls: 'icon-key', html: formeditpass, submit: function () {
            //                 if (top.$('#txtNewPassword').validatebox('isValid')) {
            //                     $.ajaxtext('security/secuser', "action=setpassword&id=" + selectRow.Id + '&password=' + top.$('#txtNewPassword').val(), function (msg) {
            //                         if (msg == "1") {
            //                             top.$('#notity').jnotifyAddMessage({ text: '密码修改成功！请牢记新密码。', permanent: false, type: 'warning' });
            //                             top.$('#d').dialog('close');
            //                         } else
            //                             alert(msg);
            //                     })
            //                 }
            //             }
            //             });
            //
            //             top.$('#loginname').text(selectRow.UserName + ' | ' + selectRow.RealName);
            //             top.$('#txtNewPassword').validatebox();
            //         } else {
            //             top.$('#notity').jnotifyAddMessage({ text: '请选择要修改密码的用户。', permanent: false, type: 'warning' });
            //             return false;
            //         }
            //     }
            // },'-',{
            //     iconCls: 'icon-save',
            //     text: '导出',
            //     handler: function(){alert('help')}
            // },'-',{
            //     iconCls: 'icon-help',
            //     text: '帮助',
            //     handler: function(){alert('help')}
            // }
        ],
        // onSelect: function(index,row){
        //     $(this).datagrid('beginEdit', index);
        // },
        // onUnselect: function(index,row){
        //     $(this).datagrid('endEdit', index);
        // },
        // onSelectAll: function(rows){
        //     for(var i =0;i<rows.length;i++){
        //         $(this).datagrid('beginEdit', i);
        //     }
        // },
        // onUnselectAll: function(rows){
        //     for(var i =0;i<rows.length;i++){
        //         $(this).datagrid('endEdit', i);
        //     }
        // }
    });
    grid.bind();

});

function updateUserRole() {
    $.messager.progress();	// display the progress bar
    var selectRow = $('#user_datagrid').datagrid('getSelected');
    var userId = selectRow.id;
    var roleId = $('#roleIdUserRole').combobox('getValue');
    $('#updateUserRoleForm').form('submit', {
        url: "/sec/updateUserRole/" + userId + "/" + roleId,
        onSubmit: function () {
            var isValid = $(this).form('validate');
            if (!isValid) {
                $.messager.progress('close');	// hide progress bar while the form is invalid
            }
            return isValid;	// return false will stop the form submission
        },
        success: function () {
            $.messager.progress('close');	// hide progress bar while submit successfully
            $('#updateUserRoleForm').form('clear');
            $('#updateUserRole').window('close');
            $('#user_datagrid').datagrid('reload');
        },
        onLoadError: function () {
            $.messager.alert("保存信息", "发生错误!", "error");
        }
    });
}

function clearUserRole() {
    $('#updateUserRole').window('close');
    $('#updateUserRoleForm').form('clear');
}

var grid = {
    bind: function () {
        var winSize = {width: $(window).width() - 4, height: $(window).height() - 4};
        $('#user_datagrid').datagrid({
            data: []
        });
        $('#user_datagrid').datagrid({
            url: "/sec/listUser.do",
            title: "系统用户列表",
            iconCls: 'icon icon-list',
            width: winSize.width,
            height: winSize.height,
            nowrap: true, //false:折行
            rownumbers: true, //行号
            striped: true, //隔行变色
            idField: 'id', //主键
            singleSelect: true, //单选
            checkOnSelect: true,
            //frozenColumns: [[]],
            columns: [[
                {field: 'ckb', checkbox: true},
                {title: '主键', field: 'id', hidden: true},
                {
                    title: '登录名',
                    field: 'loginName',
                    width: 100,
                    sortable: true,
                    editor: {type: 'validatebox', options: {required: true}}
                },
                {
                    title: '密码',
                    field: 'userPassword',
                    width: 100,
                    editor: {type: 'validatebox', options: {required: true}}
                },
                {title: '用户名', field: 'realName', width: 100},
                {title: '部门', field: 'departmentName', width: 100},
                {title: '角色主键', field: 'RoleId', hidden: true},
                // { title: '有效', field: 'Enabled', width: 50, formatter: imgcheckbox },
                {title: '邮箱地址', field: 'email', width: 100},
                {title: '手机号码', field: 'mobile', width: 100},
                {title: '描述', field: 'Description', width: 100},
                // { title: 'Enabled', field: 'Enabled', hidden: true },
                // { title: 'Gender', field: 'Gender', hidden: true },
                // { title: 'UserPassword', field: 'userPassword', hidden: true },
                // { title: 'Birthday', field: 'Birthday', hidden: true },
                // { title: 'Telephone', field: 'Telephone', hidden: true },
                // { title: 'Duty', field: 'Duty', hidden: true },
                // { title: 'QICQ', field: 'QICQ', hidden: true },
                // { title: 'Title', field: 'Title', hidden: true },
                // { title: 'RoleId', field: 'RoleId', hidden: true },
                // { title: 'CompanyId', field: 'CompanyId', hidden: true },
                // { title: 'CompanyName', field: 'CompanyName', hidden: true },
                // { title: 'DepartmentId', field: 'DepartmentId', hidden: true },
                // { title: 'DepartmentName', field: 'DepartmentName', hidden: true },
                // { title: 'WorkgroupId', field: 'WorkgroupId', hidden: true },
                // { title: 'WorkgroupName', field: 'WorkgroupName', hidden: true },
                // { title: 'HomeAddress', field: 'HomeAddress', hidden: true }
            ]]
        });
    },
    getSelectedRow: function () {
        return $('#user_datagrid').datagrid('getSelected');
    }
}


var imgcheckbox = function (cellvalue, options, rowObject) {
    return cellvalue ? '正常' : '禁用';
}

var date2str = function (cellvalue, options, rowObject) {
    if (cellvalue)
        return $D(cellvalue).strftime("%Y-%m-%d");
    else
        return '';
}

var initUIform = function () {
    top.$('#w').hWindow({
        html: pform, width: 640, height: 520, title: '添加用户', iconCls: 'icon-add', submit: function () {
            var flag = true;
            top.$('#uiform input').each(function () {
                if ($(this).attr('required') || $(this).attr('validType')) {
                    if (!top.$(this).validatebox('isValid')) {
                        flag = false;
                        return;
                    }
                }
            });


            var vRoleId = top.$('#txtRoleId').combobox('getValue');
            var vCompanyId = top.$('#txtCompanyName').combobox('getValue');
            var vDepartmentId = top.$('#txtDepartmentName').combobox('getValue');
            var vWorkgroupId = top.$('#txtWorkgroupName').combobox('getValue');
            var vCompanyName = top.$('#txtCompanyName').combobox('getText');
            var vDepartmentName = top.$('#txtDepartmentName').combobox('getText');
            var vWorkgroupName = top.$('#txtWorkgroupName').combobox('getText');
            var queryString = top.$('#uiform').serialize() + '&action=add';
            queryString = queryString + '&vRoleId=' + vRoleId + '&vCompanyId=' + vCompanyId + '&vDepartmentId=' + vDepartmentId + '&vWorkgroupId=' + vWorkgroupId;
            queryString = queryString + '&vCompanyName=' + vCompanyName + '&vDepartmentName=' + vDepartmentName + '&vWorkgroupName=' + vWorkgroupName;
            $.ajaxtext('security/secuser', queryString, function (msg) {
                if (msg == "1") {
                    top.$('#notity').jnotifyAddMessage({text: '添加成功.', permanent: false, type: 'message'});
                    top.$('#w').window('close');
                    $('#list').datagrid('reload');
                }
                else if (msg == "0") {
                    top.$('#notity').jnotifyAddMessage({text: '用户名已存，请更换用户名.', permanent: false, type: 'warning'});
                    top.$('#txtUsername').select();
                    return false;
                }
                else {
                    alert(msg);
                }
            });

            return false;
        }
    });

    top.$('#uiform input').each(function () {
        if ($(this).attr('required') || $(this).attr('validType'))
            top.$(this).validatebox();
    });
    top.$('#txtBirthday').datebox();
}

//公共方法
var pubMethod = {
    bindCategory: function (categoryControl, categoryCode) {
        if (categoryControl == '' || categoryCode == '') {
            return;
        }

        if (categoryControl == 'txtGender') {
            top.$('#' + categoryControl).combobox({
                url: 'Modules/handler/DataItemAdminHandler.ashx?action=GetCategory&categorycode=' + categoryCode,
                method: 'get',
                valueField: 'ItemValue',
                textField: 'ItemName',
                editable: false,
                panelHeight: 'auto'
            });
        }

        if (categoryControl == 'txtRoleId') {
            top.$('#' + categoryControl).combobox({
                url: 'Modules/handler/RoleAdminHandler.ashx?action=GetEnabledRoleList',
                method: 'get',
                valueField: 'Id',
                textField: 'RealName',
                editable: false,
                panelHeight: 'auto'
            });
        }

        if (categoryControl == 'txtCompanyName' || categoryControl == 'txtDepartmentName' || categoryControl == 'txtWorkgroupName') {
            top.$('#' + categoryControl).combobox({
                url: 'Modules/handler/OrganizeAdminHander.ashx?action=GetOrganizeByCategory&OrganizeCategory=' + categoryCode,
                method: 'get',
                valueField: 'Id',
                textField: 'FullName',
                editable: false,
                panelHeight: 'auto'
            });
        }
    }
}

var pform = '<form id="uiform"><table  cellpadding=5 cellspacing=0 width=100% align="center" class="grid2" border=0><tr><td align="right">';
pform += '登录用户名：</td><td><input name="UserName" id="txtUserName" validType="length[2,40]" required="true" type="text" class="txt03" ></td><td align="right">';
pform += '姓名：</td><td><input name="RealName" id="txtRealName" validType="length[2,40]" required="true" type="text" class="txt03" ></td></tr><tr><td align="right">';
pform += '编号：</td><td><input name="Code" id="txtCode" validType="length[2,40]" type="text" class="txt03" ></td><td align="right">';
pform += '用户密码：</td><td><input validType="safepass"  required="true" name="UserPassword" id="txtUserPassword"  type="password" class="txt03" ></td></tr><tr><td align="right">';
pform += '性别：</td><td><input name="Gender" id="txtGender"  required="true" type="text" class="txt03" ></td><td align="right">';
pform += '手机号码：</td><td><input name="Mobile" id="txtMobile" type="text" class="txt03" ></td></tr><tr><td align="right">';
pform += '出生日期：</td><td><input name="Birthday" id="txtBirthday" type="text" class="txt03" ></td><td align="right">';
pform += '固定电话：</td><td><input name="Telephone" id="txtTelephone" type="text" class="txt03" ></td></tr><tr><td align="right">';
pform += '岗位：</td><td><input name="Duty" id="txtDuty" type="text" class="txt03" ></td><td align="right">';
pform += 'QQ号码：</td><td><input name="QICQ" id="txtQICQ" type="text" class="txt03" ></td></tr><tr><td align="right">';
pform += '职称：</td><td><input name="Title" id="txtTitle" type="text" class="txt03" ></td><td align="right">';
pform += '邮箱地址：</td><td><input name="Email" id="txtEmail" type="text" class="txt03" ></td></tr><tr><td align="right">';
pform += '默认角色：</td><td><input name="RoleId" id="txtRoleId" type="text" class="txt03" ></td><td align="right">';
pform += '公司名称：</td><td><input name="CompanyName" id="txtCompanyName" type="text" class="txt03" ></td></tr><tr><td align="right">';
pform += '部门名称：</td><td><input name="DepartmentName" id="txtDepartmentName" type="text" class="txt03" ></td><td align="right">';
pform += '工作组：</td><td><input name="WorkgroupName" id="txtWorkgroupName" type="text" class="txt03" ></td></tr><tr><td align="right">';
pform += '家庭地址：</td><td  colspan="3"><input name="HomeAddress" style="width:470px;" id="txtHomeAddress" type="text" class="txt03" ></td></tr><tr><td align="right">';
pform += '有效性：</td><td colspan="3"><input id="chkEnabled" type="checkbox" name="Enabled" /><label>有效</label>  <span style="color:#666;padding-left:20px;">注：用户无效（禁用该用户）后，该用户将不能登录。</span></td></tr><tr><td align="right"> ';
pform += '描述：</td><td colspan =3><textarea  id="txtDescription" name="Description" rows="3" style="width:470px;height:50px;" class="txt03"></td></tr></table></form>';

var formeditpass = '<table class="grid" id="epform">';
formeditpass += '<tr><td>登录名：</td><td><span id="loginname"></span></td></tr>';
formeditpass += '<tr><td>新密码：</td><td><input  validType="safepass"  required="true" id="txtNewPassword" name="password" type="password" class="txt03" /></td></tr>';
formeditpass += '</table>';

